#!/bin/bash
outputfile=hexfile.hex
lineno=0
cat /dev/null > $outputfile
#先初始化为无效数据
LAST_LINE_CONTENT=""
while read line
do
	words=`echo $line | wc -w`
	#echo "words is $words"
	if [ 0 -lt $words ];then
		#echo "LAST_TOTAL_BINCOUNT is $LAST_TOTAL_BINCOUNT"
		lineno=`expr $lineno + 1`
		#step 1@3 计算这一行总共有多少个二进制数据
		LAST_LINE=(`echo $LAST_LINE_CONTENT | awk '{print $1}'`)
		LAST_TOTAL_BINCOUNT=$((16#${LINE[0]}))
		LINE=(`echo $line | awk '{print $1}'`)
		TOTAL_BIN_COUNT=$((16#${LINE[0]}))
		if [ 0 -lt $TOTAL_BIN_COUNT ];then
			
			LINE_BIN_COUNT=`expr ${TOTAL_BIN_COUNT} - ${LAST_TOTAL_BINCOUNT}`
			echo "[${lineno}]当前总共字节数: ${TOTAL_BIN_COUNT},上一次总共字节数: ${LAST_TOTAL_BINCOUNT},得到当前行的字节数: ${LINE_BIN_COUNT}"
			#step 2@3 组装合适的awk参数	
			AWK_COMMAND_ARGS="\{print "
			for (( i = 0; i < ${LINE_BIN_COUNT} ; i ++ ))
			do
				arg=`expr $i + 2`
				AWK_COMMAND_ARGS+="\$${arg}\" \""
			done
			AWK_COMMAND_ARGS+="}"
			
			#step 3@3 提取上一步得到的数量的二进制数据
			DATA=`echo  -e -n $LAST_LINE_CONTENT | awk '$AWK_COMMAND_ARGS'`
			#echo "AWK_COMMAND_ARGS is ${AWK_COMMAND_ARGS},LAST_LINE_CONTENT is ${LAST_LINE_CONTENT},line is $line"
			index=0
			for ele in ${DATA}
			do
				if [[ 1 -le $index && $index -le ${LINE_BIN_COUNT} ]];then	
					#echo "[$lineno]ele is \x$ele"
					echo -e -n "\x$ele" >> $outputfile
				fi
				index=`expr $index + 1`
			done
# 			if [ 16 -gt $LINE_BIN_COUNT ];then
# 				#调试,用于确认是否正确处理了当前字节数少于16个的情况
# 				echo "当前行的字节数量少于16个,请确认"
# 				exit
# 			fi
		fi
		LAST_LINE_CONTENT=$line
	fi
	#调试,用于先试验性质的跑一行数据看看
# 	break
done < /root/httprawrecv_wireshark.ts